import Vue from 'vue'
import Element from 'element-ui'
import md5 from 'js-md5'
import VueAxios from 'vue-axios'

import learunComponents from './components' // Internationalization

import axios from './router/axios'
import router from './router'
import Permission from './permission' // 权限
import UseStore, { store, storeOptions } from './store'
import i18n from './lang' // Internationalization
import App from './App'

import Mixin from './mixins/base'



import './error' // 日志
import './cache' //页面缓冲
import './styles/common.scss'

// 模块列表
import modules from './modules'

// 力软框架支持cms
const cmsConfig = {
    enable: false,
    login: false,
    authorize: false,
    appCode: undefined,
    appSign: undefined
}

export default {
    registerModule(module) {
        if (module) modules.push(...module)
    },
    use:async ({ urls,website }) => {
        // 加载相关url地址
        Object.keys(urls).forEach(key => {
            Vue.prototype[key] = urls[key]
            window[`$${key}`] = urls[key]
        })
        //注册全局组件

        Vue.use(learunComponents)

        Vue.mixin(Mixin())

        // md5

        Vue.prototype.$md5 = md5;
        Vue.config.productionTip = process.env.NODE_ENV !== 'development'
    
        Vue.use(VueAxios, axios)

        
        if(window){
            window.$axios = axios
        }


        const routes = []
        modules.forEach(m=>{
            // 注入路由信息
            m.routes && routes.push(...m.routes)
            // 注入状态信息
            m.store && (storeOptions.modules[m.module.code] = m.store)
            // 添加全局组件
            m.components && m.components.forEach(com=>{
                Vue.component(com.name, com.component)
            })

        })
        // 使用状态
        UseStore()

        //启动cms配置
        UseCMS(store)
        
        // 系统属性
        let system = {
            modules: modules.map(m => m.module),
            webconfig:website
        }

        store.dispatch('app/init', { system })
        store.commit('SET_TAGWEL', website.fistPage)// 设置首页

       

        // 注入路由信息
        const myRouter = router.use({views:routes,store})
        Object.keys(Permission).forEach(key => {
            myRouter[key](Permission[key])
        })
        Vue.use(myRouter)
        window.$router = myRouter       
        


        await  window.$awaitWraper(store.dispatch("language/type/getList"))
        // 动态加载多语言
        const mainLanguage = store.getters.appConfig.language.mainType
        const nowLanguage= store.getters.appConfig.language.type
        if(mainLanguage != nowLanguage){
            Vue.use(Element,{
                i18n: (key, value) => { 
                    return i18n.t(key, value) 
                }
            }) 
            const lgMapping = await window.$awaitWraper(window.$api.language.mapping.getList(mainLanguage,nowLanguage))
            if(lgMapping){
                i18n.setLocaleMessage('learun', Object.assign(lgMapping))
            }
        }
        else
        {
            // 加载饿了么框架
            Vue.use(Element) 
        }
       

        //Vue.config.performance = true;
        new Vue({
            router:myRouter,
            store,
            i18n,
            render: h => h(App)
        }).$mount('#app')
    },
    enableCMS({ login, authorize, appCode, appSign }) {
        Object.assign(cmsConfig, { enable: true, login, authorize, appCode, appSign })
        if(login){
            window.$api.organization.user.login = window.$api.organization.user.loginCMS
        }
    }
}

function UseCMS(store){
    if(cmsConfig.authorize){
        store.dispatch("appadmin/auth/load")

        //替换当前登录人拥有的菜单权限
        replaceLoginInfo(store)

        //替换当前系统所有的菜单信息
        replaceAllMenus(store)

        //替换按钮权限
        replaceButtons(store)

        //默认开启所有字段权限
        Vue.mixin({
            methods: {
                lr_getPageColumns(columns, pageName = '') {
                    console.log("默认开启所有字段权限 pageName", pageName)
                    return columns;
                }
            }
        })
    }

    function replaceLoginInfo (store) {
        window.$api.organization.user.getLoginInfo = () => new Promise((resolve, reject) => {
            window.$axios({
                url: 'login/pc',
                method: 'get'
            }).then((res) => {
                res.data.data.moduleAuthIds = store.state.appadmin.auth.authInfo.menus.map(t => t.id)
                resolve(res)
            }).catch(err => {
                reject(err)
            })
        })
    }
    
    function replaceAllMenus (store) {
        window.$api.system.module.getList = () => new Promise((resolve) => {
            let res = store.state.appadmin.auth.authInfo.menus.map(t => {
                return {
                    f_FullName: t.name,
                    f_Icon: t.icon,
                    f_IsMenu: 1,
                    f_EnabledMark: 1,
                    f_DeleteMark: 0,
                    f_Target: t.type === 0 ? 'expand' : 'view',
                    f_UrlAddress: t.pagePath,
                    f_EnCode: t.routeName,
                    f_SortCode: t.sort,
                    f_ParentId: t.level === 0 ? "0" : t.parentId,
                    f_ModuleId: t.id
                }
            })
            resolve({ data: {data: res}})
        })
    }

    function replaceButtons (store) {
        window.$api.permission.module.get = (id) => new Promise((resolve) => {
            let authInfo = store.state.appadmin.auth.authInfo
            let currentModule = authInfo.menus.find(t => t.id == id)

            let res = {buttons: [], columns: [], forms: []}
            if(currentModule){
                res.buttons = authInfo.buttons.filter(t => t.startsWith(`${currentModule.routeName}_`)).map(t => t.split("_")[1])
            }
            resolve({ data: {data: res}})
        })
    }
}



export { cmsConfig }